<?php
/**
 * 该类主要完成，对授权后的小程序进行处理（微信开放平台，小程序模板管理，小程序设置，上传,审核等操作）
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/10/25
 * Time: 15:18
 */

namespace app\api\service;

use app\api\model\MiniAudit;
use app\api\model\ThirdApp;
use app\lib\exception\MiniSuiteException;
use app\lib\exception\SuccessMessage;


class MiniHandle extends Mini
{
    /**
     * 获取小程序草稿列表
     * @param $uid
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getDraftList(){
        $access_token = $this->getComponentValue();
        $url = 'https://api.weixin.qq.com/wxa/gettemplatedraftlist?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
            return $data;
        }else{
            throw new MiniSuiteException([
                'msg'=>'获取小程序模板草稿失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 获取小程序模板列表
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getTemplateList(){
        $access_token = $this->getComponentValue();
        $url = 'https://api.weixin.qq.com/wxa/gettemplatelist?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
            return $data;
        }else{
            throw new MiniSuiteException([
                'msg'=>'获取小程序模板失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 设置小程序模板
     * @return mixed
     * @throws MiniSuiteException
     */
    public function addToTemplate($draft_id){
        $access_token = $this->getComponentValue();
        $url = 'https://api.weixin.qq.com/wxa/addtotemplate?access_token=%s';
        $url = sprintf($url,$access_token);
        $params=['draft_id'=>$draft_id];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
            return $data;
        }else{
            throw new MiniSuiteException([
                'msg'=>'设置小程序代码模版'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 删除小程序模板
     * @param $template_id
     * @return mixed
     * @throws MiniSuiteException
     */
    public function deleteTemplate($template_id){
        $access_token = $this->getComponentValue();
        $url = 'https://api.weixin.qq.com/wxa/deletetemplate?access_token=%s';
        $url = sprintf($url,$access_token);
        $params=['template_id'=>$template_id];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
            return $data;
        }else{
            throw new MiniSuiteException([
                'msg'=>'删除小程序模板失败，具体原因'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }



    /**
     * d第一步：设置小程序的服务器域名
     * @param $uid
     * @return bool
     * @throws MiniSuiteException
     */
    public function setServerUrl($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/modify_domain?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "action"=>"add",
            "requestdomain"=>["https://minitest.17jxyx.com","https://mini.17jxyx.com"],
            "wsrequestdomain"=>["wss://minitest.17jxyx.com","wss://mini.17jxyx.com"],
            "uploaddomain"=>["https://minitest.17jxyx.com","https://resource.17jxyx.com","https://up-z2.qbox.me"],
            "downloaddomain"=>["https://resource.17jxyx.com","https://minitest.17jxyx.com","https://wx.qlogo.cn"],
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
                return true;
        }else{
            throw new MiniSuiteException([
                'msg'=>'设置服务器域名失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 第二步：设置小程序业务域名
     * @param $uid
     * @return bool
     * @throws MiniSuiteException
     */
    public function setWebViewUrl($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/setwebviewdomain?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "action"=>"add",
            "webviewdomain"=>["https://minitest.17jxyx.com"]
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if ($data->errcode == 0){
            return true;
        }else{
            throw new MiniSuiteException([
                'msg'=>'设置小程序业务域名失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 第三步：绑定小程序体验者
     * @param $uid
     * @param $wechatId
     * @return bool
     * @throws MiniSuiteException
     */
    public function bindMember($uid,$wechatId)
    {
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/bind_tester?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "wechatid"=>$wechatId
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return new SuccessMessage();
        } else {
            throw new MiniSuiteException([
                'msg'=>'设置小程序体验者失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 解绑小程序体验者
     * @param $uid
     * @param $wechatId
     * @return bool
     * @throws MiniSuiteException
     */
    public function unBindMember($uid,$wechatId){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/unbind_tester?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "wechatid"=>$wechatId
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return new SuccessMessage();
        } else {
            throw new MiniSuiteException([
                'msg'=>'解绑小程序体验者失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 获取小程序体验者列表
     * @param $uid
     * @return mixed
     * @throws MiniSuiteException
     */
    public function listMember($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/memberauth?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "action"=>"get_experiencer",
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data->members;
        } else {
            throw new MiniSuiteException([
                'msg'=>'获取体验者列表失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 第四步：提交小程序代码
     * @param $uid
     * @param $appid
     * @param int $template_id
     * @param string $user_version
     * @param string $user_desc
     * @return bool
     * @throws MiniSuiteException
     */
    public function codeSubmit($uid,$template_id = 1, $user_version = 'v1.0.0', $user_desc = ""){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/commit?access_token=%s';
        $url = sprintf($url,$access_token);
        $ext_json =config('mini_ext_json.ext_json');
        $ext_json['ext']['attr']['id'] = $uid;//绑定小程序拥有者
        $params = [
            "template_id"=>$template_id,
            "ext_json"=>json_encode( $ext_json, JSON_UNESCAPED_UNICODE ), //*ext_json需为string类型，请参考下面的格式*
            "user_version"=>$user_version,
            "user_desc"=> $user_desc,
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return new SuccessMessage();
        } else {
            throw new MiniSuiteException([
                'msg'=>'小程序代码提交失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 获取小程序上传的体验二维码
     * @param $uid
     * @param string $path
     * @return bool
     * @throws MiniSuiteException
     */
    public function getExpVersion($uid,$path = ''){
        $access_token = $this->getAcessToken($uid);
        if ($path){
            $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token=%s&path=%s';
            $url = sprintf($url,$access_token,urlencode($path));
        }else{
            $url = 'https://api.weixin.qq.com/wxa/get_qrcode?access_token=%s';
            $url = sprintf($url,$access_token);
        }
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        $path = $this->createFolder();
        $name = md5(time());
        $result = file_put_contents($path.'/'.$name.'.jpg',$requestData,true);
        if ($data != null || !$result){
            throw new MiniSuiteException([
                'msg'=>'获取小程序体验二维码失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }else{
            return $path.'/'.$name.'.jpg';
        }
    }
    /**
     * 第五步：提交小程序代码包审核
     * @param $uid
     * @param $tag
     * @return mixed
     * @throws MiniSuiteException
     */
    public function submitReview($uid,$tag){
        $access_token = $this->getAcessToken($uid);
        $category = $this->getCategory($uid);
        $page = $this->getPage($uid);
        if(!empty($category)) {
            $first_class = $category->category_list[0]->first_class ;
            $second_class = $category->category_list[0]->second_class;
            $first_id = $category->category_list[0]->first_id;
            $second_id = $category->category_list[0]->second_id;
        }else{
            throw new MiniSuiteException([
                'msg'=>'提交授权小程序代码包审核失败',
                'error_code'=>26011
            ]);
        }
        if(!empty($page->page_list) && isset($page->page_list[0])) {
            $address =$page->page_list[0];
        }
        $url = 'https://api.weixin.qq.com/wxa/submit_audit?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "item_list"=>[
                [
                    "address"=>$address,
                    "tag"=>$tag,
                    "first_class"=>$first_class,
                    "second_class"=>$second_class,
                    "first_id"=>$first_id,
                    "second_id"=>$second_id,
                    "title"=> "名片列表"
                ]
            ]
        ];
        $requestData = curl_post_gbk($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            //添加记录
            $audit['auditid'] = $data->auditid;
            $audit['error_code'] = 0;
            $audit['msg'] = '';
            return $audit;
        } else {
            throw new MiniSuiteException([
                'msg'=>'提交授权小程序代码包审核失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**561081430
     * 获取特定版本的小程序审核状态
     * @param $uid
     * @param $auditid
     * @return bool|mixed
     * @throws MiniSuiteException
     */
    public function getAuditStatus($uid,$auditid){
        $access_token = $this->getAcessToken($uid);
        $url = ' https://api.weixin.qq.com/wxa/get_auditstatus?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "auditid"=>$auditid
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            if ($data->status == 0){
                return true;
            }
            return $data;
        } else {
            throw new MiniSuiteException([
                'msg'=>'小程序审核状态'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 查询最新一次提交的审核状态
     * @param $uid
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getLatestAudit($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/get_latest_auditstatus?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            if ($data->status == 1){
                return $data->reason;
            }
            return $data;
        } else {
            throw new MiniSuiteException([
                'msg'=>'小程序审核状态'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 小程序审核撤回
     * @param $uid
     * @return bool
     * @throws MiniSuiteException
     */
    public function unDocodeAudit($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/undocodeaudit?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return new SuccessMessage();
        } else {
            throw new MiniSuiteException([
                'msg'=>'小程序审核撤回失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 发布已审核的小程序程序
     * @param $uid
     * @return SuccessMessage
     * @throws MiniSuiteException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function release($uid){
        $access_token = $this->getAcessToken($uid);
        $url = "https://api.weixin.qq.com/wxa/release?access_token=%s";
        $url = sprintf($url,$access_token);
        $requestData = curl_post($url,[]);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            $info['status'] = 5;
            $info['reason'] = '小程序已发布';
            $appInfo =  ThirdApp::getUserAuthInfo($uid);
            MiniAudit::updateAuditById($appInfo->mini_id,$info);
            return new SuccessMessage();
        } else {
            throw new MiniSuiteException([
                'msg'=>'小程序发布失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 获取模板库列表
     * @param $uid
     * @param $page
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getAllTemplate($uid,$page){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/library/list?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
           "offset"=>intval($page),
            "count"=>20,
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data;
        } else {
            throw new MiniSuiteException([
                'msg'=>'请求模板标签库失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 板库某个模板标题下关键词库
     * @param $uid
     * @param $id
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getTemplateDetail($uid,$id){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/library/get?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "id"=>$id,
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data->keyword_list;
        } else {
            throw new MiniSuiteException([
                'msg'=>'请求模板标签库失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 添加消息模板
     * @param $uid
     * @param $id 模板id
     * @param $keyword_id 关键字ID
     * @return mixed
     * @throws MiniSuiteException
     */
    public function addTemplate($uid,$id,$keyword_id){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/add?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "id"=>$id,
            "keyword_id_list"=>$keyword_id
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data->template_id;//模板消息ID
        } else {
            throw new MiniSuiteException([
                'msg'=>'请求模板标签库失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 获取已存在的小程序模板列表
     * @param $uid
     * @param $page
     * @return mixed
     * @throws MiniSuiteException
     */
    public function getExistTemplateList($uid,$page){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=%s';
        $url = sprintf($url,$access_token);
        $params = [
            "offset"=>$page,
            "count"=>20
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data->keyword_list;
        } else {
            throw new MiniSuiteException([
                'msg'=>'请求模板标签库失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 获取授权小程序帐号的可选类目
     * @param $uid
     * @return mixed
     * @throws MiniSuiteException
     */
    private function getCategory($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/get_category?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data;
        } else {
            throw new MiniSuiteException([
                'msg'=>'获取授权小程序帐号的可选类目失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 获取小程序的第三方提交代码的页面配置失败
     * @param $uid
     * @return mixed
     * @throws MiniSuiteException
     */
    private function getPage($uid){
        $access_token = $this->getAcessToken($uid);
        $url = 'https://api.weixin.qq.com/wxa/get_page?access_token=%s';
        $url = sprintf($url,$access_token);
        $requestData = curl_get($url);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data;
        } else {
            throw new MiniSuiteException([
                'msg'=>'获取小程序的第三方提交代码的页面配置失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }

    /**
     * 解绑小程序
     * @param $appid
     * @return mixed
     * @throws MiniSuiteException
     */
    public function unbundAuthor($uid){
        $result =  ThirdApp::getDetailUserInfoByMini($uid);
        if (empty($result->mini)){
            throw new MiniSuiteException([
                'code'=>203,
                'msg'=>'还未授权小程序',
                'error_code'=>26016
            ]);
        }
        $access_token = $this->getAccessToken($result->mini->authorizer_appid);//获取access_token
        $url = 'https://api.weixin.qq.com/cgi-bin/open/unbind?access_token=%s';
        $url = sprintf($url,$access_token);
        $params=[
            'appid'=>$result->mini->authorizer_appid,
            'open_appid'=>$this->appId,
        ];
        $requestData = curl_post($url,$params);
        $data = json_decode($requestData);
        if($data->errcode == 0) {
            return $data;
        } else {
            throw new MiniSuiteException([
                'code'=>203,
                'msg'=>'解绑小程序失败'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }
    }
    /**
     * 获取access_token
     * @param $uid
     * @return bool|mixed
     */
    private function getAcessToken($uid){
        $info = ThirdApp::getDetailUserInfoByMini($uid);
        $appid = $info->mini->authorizer_appid;
        if (cache($appid)){
            $access_token = json_decode(cache($appid));
        }else{
            $mini = new Mini();
            $access_token =  $mini->getAccessToken($appid);
        }
        return $access_token;
    }

    /**
     * 创建文件夹
     * @return string
     */
    private function createFolder(){
        $data =  date('Ymd',time());
        $path = './mini/'.$data;
        if (!is_dir($path)){
            mkdir('./mini/'.$data,0777);
        }
        return $path;
    }


}